import { iaxios } from './index.js';
//模拟数据除了安灯页面的数据信息
class CApi {
    _api;
    constructor(server) {
        let baseApi = import.meta.env.VITE_API;
        if (import.meta.env.DEV) {}
        this._api = new iaxios(baseApi);
        return this._api;
    }
}

const _api = new CApi();

class capi {
    acmd = "api/Read/GetDemoSceneDat";
    pathId;
    constructor(id) {
        this.pathId = id;
    }

    async getDemoData(sceneId, mId = null, pId = null,lId = null) {
        let url = `${this.acmd}/${sceneId}`;
        if (mId !== null) {
            url += `/${mId}`;
            if (pId !== null) {
                    url += `/${pId}`;
                    if (lId !== null) {
                        url += `/${lId}`;
                    }
                }
            }
        try {
            const response = await _api.hDo({
                param: url,
                method: "get"
            });

            // 直接返回response，因为它已经是正确的格式了
            return response;
        } catch (error) {
            console.error('获取数据失败:', error);
            return null;
        }
    }
}

/**
 * Mock数据接口
 */
class cMock extends capi {
    constructor() {
        super(300); // 使用新的 pathId
    }

    /**
     * 获取模拟数据
     * @param {Object} params 请求参数
     */
    async getMockData(params) {
        let d = await this.getList(`getMockData`, params);
        return d?.data;
    }

    /**
     * 设置模拟数据
     * @param {Object} data 要设置的数据
     */
    async setMockData(data) {
        let d = await this.getList(`setMockData`, data);
        return d?.data;
    }

    /**
     * 获取模拟设备状态
     * @param {string} deviceId 设备ID
     */
    async getDeviceStatus(deviceId) {
        let d = await this.getList(`getDeviceStatus?deviceId=${deviceId}`);
        return d?.data;
    }

    /**
     * 设置模拟设备状态
     * @param {string} deviceId 设备ID
     * @param {Object} status 设备状态
     */
    async setDeviceStatus(deviceId, status) {
        let d = await this.getList(`setDeviceStatus`, {
            deviceId,
            status
        });
        return d?.data;
    }
}

/**
 * 场景数据接口
 */
class cSceneData extends capi {
    constructor() {
        super(68);
    }

    /**
     * 获取指定板块的数据
     * @param {number} blockIndex - 板块索引，0:生产概况，1:月产品缺料统计，2:报警统计，3:设备运行统计，4:近月能耗
     * @returns {Promise<Object>} 返回数据结构示例:
     * {
     *   title: string,
     *   data: Array<{name: string, url: string, value: number, unit: string}>
     * }
     */
    async getBlockData(blockIndex) {
        try {
            const response = await this.getDemoData(68, 1);
            console.log(`getBlockData[${blockIndex}] response:`, response);

            if (!response?.data?.[blockIndex]?.list) {
                console.warn(`Block data ${blockIndex} or its list is missing`);
                return { title: "数据未找到", data: [] };
            }

            const blockData = response.data[blockIndex];

            // 定义不同板块的图标和单位映射
            const mappings = {
                0: { // 生产概况
                    '任务总数': { url: "/imgs/hf/1.png", unit: "单" },
                    '完成任务': { url: "/imgs/hf/1.png", unit: "单" },
                    '延期任务': { url: "/imgs/hf/1(1).png", unit: "件" },
                    '进行中任务': { url: "/imgs/hf/组 1632.png", unit: "件" }
                }
                // 可以添加其他板块的映射
            };

            // 使用对应板块的映射，如果没有则使用默认值
            const itemMapping = mappings[blockIndex] || {};

            // 转换数据格式
            const data = blockData.list.map(item => {
                const mappedData = itemMapping[item.atrName] || {
                    url: "/imgs/hf/1.png",
                    unit: "单"
                };
                
                return {
                    name: item.atrName,
                    url: mappedData.url,
                    value: item.valFloat || 0,
                    unit: mappedData.unit
                };
            });

            return {
                title: blockData.name,
                data: data
            };

        } catch (error) {
            console.error(`获取板块${blockIndex}数据失败:`, error);
            return { title: "数据获取失败", data: [] };
        }
    }

    // 生产概况数据
    async getProductionOverview() {
        return this.getBlockData(0);
    }

    // 月产品缺料统计
    async getMonthlyMaterialShortage() {
        try {
            const response = await this.getDemoData(68, 1);
            console.log('getMonthlyMaterialShortage response:', response);

            if (!response?.data?.[1]?.list) {
                console.warn('Monthly material shortage data is missing');
                return {
                    title: "月产品缺料统计",
                    chartData: {
                        names: ['暂无数据'],
                        values: [0]
                    }
                };
            }

            const blockData = response.data[1]; // 获取第二个数据块（月产品缺料统计）
            
            // 过滤掉第一条数据（标题数据）并转换数据格式
            const chartData = blockData.list
                .filter(item => item.datType === 1) // 只取数字类型的数据
                .reduce((acc, item) => {
                    acc.names.push(item.atrName);
                    acc.values.push(item.valFloat || 0);
                    return acc;
                }, { names: [], values: [] });

            return {
                title: blockData.name,
                chartData: chartData
            };

        } catch (error) {
            console.error('获取月产品缺料统计数据失败:', error);
            return {
                title: "月产品缺料统计",
                chartData: {
                    names: ['暂无数据'],
                    values: [0]
                }
            };
        }
    }

    // 报警统计
    async getAlarmStatistics() {
        try {
            const response = await this.getDemoData(68, 1);
            console.log('getAlarmStatistics response:', response);

            if (!response?.data?.[2]?.list) {
                console.warn('Alarm statistics data is missing');
                return {
                    title: "报警统计",
                    data: [
                        { name: '本日报警数', value: 0 },
                        { name: '本周报警数', value: 0 },
                        { name: '本月报警数', value: 0 }
                    ]
                };
            }

            const blockData = response.data[2]; // 获取第三个数据块（报警统计）
            
            // 转换数据格式
            const data = blockData.list.map(item => {
                return {
                    name: item.atrName,
                    value: item.valFloat || 0
                };
            });

            return {
                title: blockData.name,
                data: data
            };

        } catch (error) {
            console.error('获取报警统计数据失败:', error);
            return {
                title: "报警统计",
                data: [
                    { name: '本日报警数', value: 0 },
                    { name: '本周报警数', value: 0 },
                    { name: '本月报警数', value: 0 }
                ]
            };
        }
    }

    // 设备运行统计
    async getDeviceRunningStats() {
        try {
            const response = await this.getDemoData(68, 1);
            console.log('getDeviceRunningStats response:', response);

            if (!response?.data?.[3]?.list) {
                console.warn('Device running statistics data is missing');
                return {
                    title: "设备运行统计",
                    secondTitle: "设备数量",
                    totalDevices: 100,
                    deviceStatus: [
                        { name: "运行", value: 54, color: "#1AFFC6" },
                        { name: "停止", value: 17, color: "#FFE71C" },
                        { name: "故障", value: 1, color: "#FF7113" },
                        { name: "待料", value: 3, color: "#0090FF" }
                    ],
                    pieData: [
                        { name: "", value: 54 },
                        { name: "", value: 17 },
                        { name: "", value: 1 },
                        { name: "", value: 3 }
                    ]
                };
            }

            const blockData = response.data[3]; // 获取第四个数据块（设备运行统计）
            
            // 设备状态颜色映射
            const colorMap = {
                "运行": "#1AFFC6",
                "停止": "#FFE71C",
                "故障": "#FF7113",
                "待料": "#0090FF"
            };
            
            // 提取总设备数量（假设第一条记录是总数）
            let totalDevices = 100; // 默认值
            let secondTitle = "设备数量";
            const totalRecord = blockData.list.find(item => item.atrName.includes("总"));
            if (totalRecord) {
                totalDevices = totalRecord.valFloat || 100;
                secondTitle = totalRecord.atrName || "设备数量";
            }
            
            // 提取各状态设备数量，排除总设备数量
            const deviceStatus = blockData.list
                .filter(item => !item.atrName.includes("总") && item.datType === 1)
                .map(item => {
                    return {
                        name: item.atrName,
                        value: item.valFloat || 0,
                        color: colorMap[item.atrName] || "#0090FF" // 使用映射的颜色或默认颜色
                    };
                });
                
            // 为饼图准备数据
            const pieData = deviceStatus.map(item => {
                return { name: "", value: item.value };
            });

            return {
                title: blockData.name,
                secondTitle: secondTitle,
                totalDevices: totalDevices,
                deviceStatus: deviceStatus,
                pieData: pieData
            };

        } catch (error) {
            console.error('获取设备运行统计数据失败:', error);
            return {
                title: "设备运行统计",
                secondTitle: "设备数量",
                totalDevices: 100,
                deviceStatus: [
                    { name: "运行", value: 54, color: "#1AFFC6" },
                    { name: "停止", value: 17, color: "#FFE71C" },
                    { name: "故障", value: 1, color: "#FF7113" },
                    { name: "待料", value: 3, color: "#0090FF" }
                ],
                pieData: [
                    { name: "", value: 54 },
                    { name: "", value: 17 },
                    { name: "", value: 1 },
                    { name: "", value: 3 }
                ]
            };
        }
    }

    // 近月能耗统计
    async getRecentEnergyConsumption() {
        try {
            const response = await this.getDemoData(68, 1);
            console.log('getRecentEnergyConsumption response:', response);

            if (!response?.data?.[4]?.list) {
                console.warn('Recent energy consumption data is missing');
                return this.getDefaultEnergyData();
            }

            const blockData = response.data[4]; // 获取第五个数据块（近月能耗统计）
            
            // 提取图表所需的x轴和y轴数据
            const xAxisData = [];
            const yAxisData = [];
            
            // 过滤出有效的数据项
            const validItems = blockData.list.filter(item => 
                item.datType === 1 && item.atrName && item.valFloat !== undefined
            );
            
            if (validItems.length > 0) {
                // 按日期排序（如果是日期格式）
                validItems.sort((a, b) => {
                    // 尝试解析日期格式（如"月.日"）
                    if (/^\d+\.\d+$/.test(a.atrName) && /^\d+\.\d+$/.test(b.atrName)) {
                        const [aMonth, aDay] = a.atrName.split('.').map(Number);
                        const [bMonth, bDay] = b.atrName.split('.').map(Number);
                        
                        if (aMonth !== bMonth) {
                            return aMonth - bMonth;
                        }
                        return aDay - bDay;
                    }
                    // 如果不是日期格式，按原始顺序
                    return 0;
                });
                
                // 提取x轴和y轴数据
                validItems.forEach(item => {
                    // 格式化名称（如果是日期格式）
                    let name = item.atrName;
                    if (/^\d+\.\d+$/.test(name)) {
                        const [month, day] = name.split('.');
                        name = `${month}月${day}日`;
                    }
                    
                    xAxisData.push(name);
                    // 根据需要转换数值（例如除以1000）
                    yAxisData.push(item.valFloat / 1000);
                });
            } else {
                // 如果没有有效数据，使用默认数据
                return this.getDefaultEnergyData();
            }

            return {
                title: blockData.name || "近月能耗统计",
                xAxis: xAxisData,
                yAxis: yAxisData,
                unit: 'kwh'
            };

        } catch (error) {
            console.error('获取近月能耗统计数据失败:', error);
            return this.getDefaultEnergyData();
        }
    }

    // 获取默认能耗数据
    getDefaultEnergyData() {
        return {
            title: "近月能耗统计",
            xAxis: ['1月', '2月', '3月', '4月', '5月'],
            yAxis: [40, 80, 60, 50, 70],
            unit: 'kwh'
        };
    }

    async getEnergyDeviceData() {
        try {
            const response = await this.getDemoData(68, 2);
            console.log('getEnergyDeviceData response:', response);
            
            if (!response?.data?.[0]?.list) {
                console.warn('Energy device data is missing');
                return this.getDefaultEnergyDeviceData();
            }
            
            const blockData = response.data[0]?.list;
            
            // 处理数据，保留原始的 atrName 和 valFloat 字段
            const devices = blockData.map(item => ({
                atrName: item.atrName || '',
                valFloat: item.valFloat || 0
            }));
            
            return {
                // 返回完整的设备列表，保留原始字段
                devices: devices,
                //在返回一个title
                title: response.data[0]?.name || '能耗设备'
            };
        } catch (error) {
            console.error('获取能耗设备数据失败:', error);
            return this.getDefaultEnergyDeviceData();
        }
    }

    // 获取默认能耗设备数据
    getDefaultEnergyDeviceData() {
        return {
            devices: [
                { atrName: "电表", valFloat: 0 },
                { atrName: "水表", valFloat: 0 }
            ],
            electricMeter: 0,
            waterMeter: 0
        };
    }
    async getAlarmTotalData(){
        try {
            const response = await this.getDemoData(68, 2);
            console.log('getEnergyDeviceData response:', response);
            
            if (!response?.data?.[1]?.list) {
                console.warn('Energy device data is missing');
                return {
                    title: "告警统计",
                    data: [
                        { name: '本日报警数', value: 20 },
                        { name: '本周报警数', value: 100 },
                        { name: '本月报警数', value: 200 }
                    ]
                }
            }
            
            const blockData = response.data[1]?.list;
            const AlarmMerbers = blockData.map(item => ({
                atrName: item.atrName || '',
                valFloat: item.valFloat || 0
            }));
            
            return {
                // 返回完整的设备列表，保留原始字段
                AlarmMerbers: AlarmMerbers,
                //在返回一个title
                title: response.data[1]?.name || '告警统计'
            };
        } catch (error) {
            console.error('告警统计获取失败:', error);
        }
    }
    //列表数据
    async getAlarmListData(){
        try {
            const response = await this.getDemoData(68, 2,9,1);
            if(!response?.data){
                
                return {
                    title: "告警列表",
                    data: []
                }
            }
            const listHead = response.data[0];
            //定义列表为response的除第一个子数组之外的所有子数组
            const listData = response.data.slice(1);
            const title =await this.getDemoData(68, 2).then(res=>res.data[2]?.name||'告警列表');
            return {
                title: title,
                listHead: listHead,
                listData: listData
            }
        } catch (error) {
            console.error('获取告警列表数据失败:', error);
        }
    }
    //右侧的第一个版面
    async getRightFirstData(){
        try {
            // const response = await this.getDemoData(68, 2);
            const response = await this.getDemoData(68, 2);
            if(!response?.data[3]?.list){
                return {
                    title: "水电统计",
                    data: []
                }   
            }
            const title = response.data[3].name;
            const blockData = response.data[3].list;
            return {
                title: title,
                XAxis: blockData.map(item => item.atrName),
                YAxis: blockData.map(item => item.valFloat)
            }
        } catch (error) {
            console.error('获取右侧第一个版面数据失败:', error);
        }
    }
    async getRightSecondData(){
        try {
            const response = await this.getDemoData(68, 2);
            if(!response?.data[4]?.list){
                return {
                    title: "用水统计",
                    data: []
                }
            }
            const title = response.data[4].name;
            const blockData = response.data[4].list;
            return {
                title: title,
                XAxis: blockData.map(item => item.atrName),
                YAxis: blockData.map(item => item.valFloat)
            }
        } catch (error) {
            console.error('获取右侧第二个版面数据失败:', error);
        }
    }
    //能耗版面
    //** 获取能耗设备数据*/
    /**


     * 获取场景数据
     * @param {number} sceneId - 场景ID
     * @param {number} [mId] - 模块ID（可选）
     * @param {number} [pId] - 板块ID（可选）
     * @returns {Promise<Object>} 返回数据结构示例:
     * {
     *   code: 200,
     *   date: "2025-02-28 05:21:00",
     *   msg: "操作成功",
     *   data: [{
     *     mName: "模块名称",
     *     pName: "板块名称",
     *     sceneId: 场景id,
     *     mId: 模块id,
     *     palId: 板块id,
     *     atrName: "属性名称",
     *     valText: "文字",
     *     valFloat: 数字,
     *     valPic: "图片全路径",
     *     valVideo: "视频全路径",
     *     valHtml: "html代码",
     *     deleteStatus: 是否删除,
     *     datType: 数据类型id
     *   }]
     * }
     */
    async getSceneData(sceneId = this.pathId, mId = null, pId = null) {
        return await this.getDemoData(sceneId, mId, pId);
    }

    /**
     * 获取指定类型的数据
     * @param {number} sceneId - 场景ID
     * @param {number} dataType - 数据类型ID
     * 数据类型说明:
     * 1: 数字
     * 2: 文本
     * 3: 图片
     * 4: 视频
     * 5: html域
     */
    async getDataByType(sceneId = this.pathId, dataType) {
        const response = await this.getDemoData(sceneId);
        if (response && response.data) {
            return response.data.filter(item => item.datType === dataType);
        }
        return [];
    }
}

const callApi = () => {
    return {
        mock: new cMock(),
        scene: new cSceneData()
    }
}

export default callApi;

/**
 * 模板类
 */
class cTemplate extends capi {
    constructor() {
        super(301);
    }

    /**
     * 获取数据
     * @param {Object} params 请求参数
     */
    async getData(params) {
        let d = await this.getList(`getData`, params);
        /**
         * 返回数据结构
         * {
         *   code: number,
         *   message: string,
         *   data: any
         * }
         */
        return d?.data;
    }
} 
